package com.ls.controller.interceptor;

import com.ls.annotation.LoginRequired;
import com.ls.util.CommunityConstant;
import com.ls.util.CommunityUtil;
import com.ls.util.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 拦截加了自定义注解 @LoginRequired 的请求
 *
 * @author ls
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    UserContextHolder userContextHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断拦截到的是否是方法
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 获取 @LoginRequired 注解
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);

            String xRequestedWith = request.getHeader("x-requested-with");
            // 需要登录，用户没有登录
            if (loginRequired != null && userContextHolder.getUser() == null) {
                // 如果是异步请求
                if (CommunityConstant.XML_HTTP_REQUEST.equals(xRequestedWith)) {
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(CommunityUtil.getJSONString(302, "您还未登录,请登录!"));
                } else {
                    response.sendRedirect(request.getContextPath() + "/login");
                }
                return false;
            }
        }
        return true;
    }
}
